package com.activity.fragment;

import static com.growingio.android.sdk.track.utils.ThreadUtils.runOnUiThread;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.activity.login.LoginActivity;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.login.R;
import com.tools.Address;
import com.tools.GoodNews;
import com.tools.HomeAllGoods;
import com.tools.OkHttp3;
import com.tools.ViewPagerAdapter;
import com.tools.goods.Goods;
import com.tools.seckillgoods.SecKillGoods;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HomeFragment extends Fragment {
    private GoodNews firstNews, secNews, thirdNews; //喜讯
    private ViewPager2 viewPager;
    private View loginDialog;
    private LinearLayout dotLinear, addLinear;
    private int lastPosition; //轮播图最后所在位置
    private HomeAllGoods firstGoods, secGoods, thirdGoods; //最热产品
    private HomeAllGoods firstSecGoods, secSecGoods, thirdSecGoods; //秒杀爆款
    private ArrayList<HomeAllGoods> suggestGoods = new ArrayList<HomeAllGoods>();
    private ArrayList<HomeAllGoods> suggestSecGoods = new ArrayList<HomeAllGoods>();
    private List<Integer> imageList = new ArrayList<>();
    private JSONObject goodsJSON; //goods
    private JSONObject secJSON; //secGoods
    private Handler mHandler = new Handler();
    private boolean isLogin = false;

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case 0x001:
                    JSONObject listObject = goodsJSON.getJSONObject("data");
                    JSONArray itemsArray = listObject.getJSONArray("items");
                    for (int i=0; i<3; i++){
                        JSONObject goodsObject = itemsArray.getJSONObject(i);
                        Goods goods = new Goods();
                        String id = goodsObject.getString("id");
                        String name = goodsObject.getString("goodsName");

                        goods.setId(id);
                        goods.setName(name);
                        goods.setGoodsCode(goodsObject.getString("goodsCode"));
                        goods.setProductDeadline(goodsObject.getInteger("productDeadline"));
                        goods.setAnnualInterestRate(goodsObject.getDouble("annualInterestRate"));
                        goods.setMinAmount(goodsObject.getInteger("minAmount"));
                        goods.setIncreasingAmount(goodsObject.getInteger("increasingAmount"));
                        goods.setLimitForOne(goodsObject.getInteger("limitForOne"));
                        goods.setLimitForDay(goodsObject.getInteger("limitForDay"));
                        goods.setRiskGrade(goodsObject.getInteger("riskGrade"));
                        goods.setValueDate(goodsObject.getString("valueDate"));
//                        goods.setInterestSettlementWay(goodsObject.getInteger("interestSettlementWay"));
                        goods.setDueDate(goodsObject.getString("dueDate"));

                        suggestGoods.get(i).setGoodsData(goods);
                    }
                    break;
                case 0x002:
                    //secGoods list
                    JSONObject listObject1 = secJSON.getJSONObject("data");
                    JSONArray itemsArray1 = listObject1.getJSONArray("items");
                    for (int i=0; i<3; i++){
                        JSONObject secObject = itemsArray1.getJSONObject(i);
                        SecKillGoods secGoods = new SecKillGoods();
                        String id = secObject.getString("id");
                        String name = secObject.getString("goodsName");

                        secGoods.setId(id);
                        secGoods.setName(name);
                        secGoods.setGoodsCode(secObject.getString("goodsCode"));
                        secGoods.setProductDeadline(secObject.getInteger("productDeadline"));
                        secGoods.setAnnualInterestRate(secObject.getFloat("annualInterestRate"));
                        secGoods.setMinAmount(secObject.getInteger("minAmount"));
                        secGoods.setIncreasingAmount(secObject.getInteger("increasingAmount"));
                        secGoods.setLimitForOne(secObject.getInteger("limitForOne"));
                        secGoods.setLimitForDay(secObject.getInteger("limitForDay"));
                        secGoods.setRiskGrade(secObject.getInteger("riskGrade"));
                        secGoods.setValueDate(secObject.getString("valueDate"));
                        secGoods.setInterestSettlementWay(secObject.getInteger("interestSettlementWay"));
                        secGoods.setDueDate(secObject.getString("dueDate"));
                        secGoods.setSecKillGoodsId(secObject.getString("seckillGoodsId"));
                        secGoods.setSecKillPrice(secObject.getInteger("seckillPrice"));
                        secGoods.setSecKillStock(secObject.getInteger("stockCount"));
                        secGoods.setStartDate(secObject.getString("startDate"));
                        secGoods.setEndDate(secObject.getString("endDate"));

                        suggestSecGoods.get(i).setSecGoodsData(secGoods);
                    }
                    break;
            }
            return false;
        }
    });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home,container,false);
        firstNews = view.findViewById(R.id.home_news_first);
        secNews = view.findViewById(R.id.home_news_second);
        thirdNews = view.findViewById(R.id.home_news_third);

        firstNews.setTitle("喜讯|参加活动领取指定秒杀产品折上折优惠");
        secNews.setTitle("公告|本周内查获四起利用脚本程序参加秒杀活动，人员名单如下");
        secNews.setImage(R.drawable.good_news_warn);
        thirdNews.setTitle("喜讯|多个产品提高满期利率");

        firstGoods = view.findViewById(R.id.home_goods_first);
        secGoods = view.findViewById(R.id.home_goods_second);
        thirdGoods = view.findViewById(R.id.home_goods_third);

        firstSecGoods = view.findViewById(R.id.home_sec_first);
        secSecGoods = view.findViewById(R.id.home_sec_second);
        thirdSecGoods = view.findViewById(R.id.home_sec_third);

        viewPager = view.findViewById(R.id.home_viewpager);
        dotLinear = view.findViewById(R.id.home_dot_container);
        addLinear = view.findViewById(R.id.home_add_linear);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        String state = Objects.requireNonNull(getActivity()).getIntent().getStringExtra("state");

        loginDialog = View.inflate(getContext(), R.layout.login_dialog, null);
        addLinear.addView(loginDialog, 0);
        Button login = loginDialog.findViewById(R.id.login_dialog_button);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
            }
        });

        if (("1").equals(state)){
            addLinear.removeView(loginDialog);
        }

        suggestGoods.add(firstGoods);
        suggestGoods.add(secGoods);
        suggestGoods.add(thirdGoods);

        suggestSecGoods.add(firstSecGoods);
        suggestSecGoods.add(secSecGoods);
        suggestSecGoods.add(thirdSecGoods);

        initData();
        initViewPager();
    }

    @Override
    public void onResume() {
        super.onResume();
        mHandler.postDelayed(runnable,3000);
    }

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeCallbacks(runnable);
    }

    private final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //获得轮播图当前的位置
            int currentPosition = viewPager.getCurrentItem();
            currentPosition++;
            viewPager.setCurrentItem(currentPosition,true);
            mHandler.postDelayed(runnable,3000);
        }
    };

    private void initData(){
        JSONObject jsonObject = new JSONObject();
        JSONObject pageJson = new JSONObject();
        JSONObject sortJson = new JSONObject();
        JSONObject queryJson = new JSONObject();
        pageJson.put("current", "1");
        pageJson.put("size", "20");

        jsonObject.put("page", pageJson);
        jsonObject.put("sort", sortJson);
        jsonObject.put("query", queryJson);
        RequestBody body = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), jsonObject.toJSONString());

        OkHttp3.sendOkHttpPostRequest(Address.getGoodsList(), body, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(),"服务器连接失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                goodsJSON = JSONObject.parseObject(res);
                Log.d("goodsFragment", goodsJSON.toString());
                if (goodsJSON.getString("code").charAt(0) == '2'){
                    handler.sendEmptyMessage(0x001);
                }else if (goodsJSON.getString("code").charAt(0) == '5'){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), goodsJSON.getString("message"),Toast.LENGTH_SHORT).show();
                        }
                    });
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "连接出错了",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });

        OkHttp3.sendOkHttpPostRequest(Address.getSecGoodsList(), body, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(),"服务器连接失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                secJSON = JSONObject.parseObject(res);
                if (secJSON.getString("code").charAt(0) == '2'){
                    handler.sendEmptyMessage(0x002);
                }else if (secJSON.getString("code").charAt(0) == '5'){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), secJSON.getString("message"),Toast.LENGTH_SHORT).show();
                        }
                    });
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "连接出错了",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    private void initViewPager(){
        imageList.add(R.drawable.test_img1);
        imageList.add(R.drawable.test_img2);
        imageList.add(R.drawable.test_img3);
        imageList.add(R.drawable.test_img4);

        initDotLinear();

        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(imageList);
        viewPager.setAdapter(viewPagerAdapter);
        //设置轮播图初始位置在500,以保证可以手动前翻
        viewPager.setCurrentItem(500);
        //最后所在的位置设置为500
        lastPosition = 500;

        //注册轮播图的滚动事件监听器
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                //轮播时，改变指示点
                int current = position % 4;
                int last = lastPosition % 4;
                dotLinear.getChildAt(current).setBackgroundResource(R.drawable.dot_selected);
                dotLinear.getChildAt(last).setBackgroundResource(R.drawable.dot_un_selected);
                lastPosition = position;
            }
        });
    }

    private void initDotLinear(){
        for(int i = 0; i < imageList.size(); i++){
            ImageView imageView = new ImageView(getContext());
            if (i == 0) imageView.setBackgroundResource(R.drawable.dot_selected);
            else imageView.setBackgroundResource(R.drawable.dot_un_selected);
            //为指示点添加间距
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.setMarginEnd(4);
            imageView.setLayoutParams(layoutParams);
            //将指示点添加进容器
            dotLinear.addView(imageView);
        }
    }
}
